package com.studentrecipe.controller;

import com.studentrecipe.mapper.MapperCreateRecipe;
import com.studentrecipe.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@RestController
@CrossOrigin
public class ControllerCreateRecipe {

    @Autowired
    private MapperCreateRecipe mapperCreateRecipe;

    @RequestMapping("/createRecipe")
    public Result createRecipe(
            Integer userId,
            String title, String description, String steps, Integer cookingTime, String difficulty, String cuisine, String calorieLevel, LocalDate createdTime,
            String[] ingredient,
            String[] flavors,
            @RequestBody MultipartFile[] images) {
        mapperCreateRecipe.insertRecipe(userId, title, description, steps, cookingTime, difficulty, cuisine, calorieLevel, createdTime);
        Integer recipeId = mapperCreateRecipe.getLastRecipeId();
        mapperCreateRecipe.insertIngredient(recipeId, ingredient);
        mapperCreateRecipe.insertFlavor(recipeId, flavors);

        if (images != null) {
            if (insertImage(recipeId, images)) {
                return Result.success("home.html");
            } else {
                return Result.fail("Image upload failed");
            }
        } else {
            return Result.success("home.html");
        }
    }

    @RequestMapping("/updateRecipe")
    public Result updateRecipe(
            Integer recipeId,
            String title, String description, String steps, Integer cookingTime, String difficulty, String cuisine, String calorieLevel,
            String[] ingredient,
            String[] flavors,
            @RequestBody MultipartFile[] images
    ) {
        mapperCreateRecipe.updateRecipe(recipeId, title, description, steps, cookingTime, difficulty, cuisine, calorieLevel);

        mapperCreateRecipe.deleteIngredient(recipeId);
        mapperCreateRecipe.insertIngredient(recipeId, ingredient);

        mapperCreateRecipe.deleteFlavor(recipeId);
        mapperCreateRecipe.insertFlavor(recipeId, flavors);

        List<String> filenames = mapperCreateRecipe.getFileName(recipeId);
        if (deleteImage(recipeId, filenames)) {
            if (images != null) {
                if (insertImage(recipeId, images)) {
                    return Result.success("update success");
                } else {
                    return Result.fail("Image upload failed");
                }
            } else {
                return Result.success("update success");
            }
        } else {
            return Result.fail("Image delete failed");
        }
    }

    @RequestMapping("/deleteRecipe")
    public Result deleteRecipe(Integer recipeId) {
        mapperCreateRecipe.deleteRecipe(recipeId);

        mapperCreateRecipe.deleteIngredient(recipeId);

        mapperCreateRecipe.deleteFlavor(recipeId);

        List<String> filenames = mapperCreateRecipe.getFileName(recipeId);
        if (deleteImage(recipeId, filenames)) {
            return Result.success("delete success");
        } else {
            return Result.fail("Image delete failed");
        }
    }

    public boolean insertImage(Integer recipeId, MultipartFile[] images) {
        String frontendImageDir = "D:\\CDUT\\England\\IPD\\cs\\ipd_front_end\\src\\img";
        File dir = new File(frontendImageDir);
        if (!dir.exists()) {
            dir.mkdirs(); // 如果目录不存在则创建
        }
        for (MultipartFile image : images) {
            if (!image.isEmpty()) {
                try {
                    String originalFilename = image.getOriginalFilename();
                    String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmssSSS");
                    String timestamp = LocalDateTime.now().format(formatter);
                    String newFilename = timestamp + extension;

                    File dest = new File(dir, newFilename);
                    image.transferTo(dest); // 保存图片到前端目录

                    // 这里你可以把 newFilename 或 dest.getPath() 存入数据库
                    mapperCreateRecipe.insertFile(recipeId, newFilename);

                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
            }
        }
        return true;
    }

    public boolean deleteImage(Integer recipeId, List<String> filenames) {
        // 1. 定义文件存储路径（建议从配置文件中读取）
        String frontendImageDir = "D:\\CDUT\\England\\IPD\\cs\\ipd_front_end\\src\\img";

        boolean isDeleted = false;

        if(filenames.isEmpty()){
            return true;
        }

        for (String filename : filenames) {
            // 2. 构建完整文件路径
            File fileToDelete = new File(frontendImageDir, filename);

            // 3. 安全校验
            if (!fileToDelete.exists()) {
                System.out.println("文件不存在: " + fileToDelete.getAbsolutePath());
                return false;
            }

            if (!fileToDelete.canWrite()) {
                System.out.println("没有文件删除权限: " + fileToDelete.getAbsolutePath());
                return false;
            }

            // 4. 执行删除操作
            isDeleted = fileToDelete.delete();
        }

        // 5. 数据库记录清理（根据业务需求决定）
        if (isDeleted) {
            // 删除数据库中的文件记录
            mapperCreateRecipe.deleteFile(recipeId);
        }

        return isDeleted;
    }
}
